package com.atdfrz.secondshop.controller.user;

import com.atdfrz.secondshop.mapper.AddressMapper;
import com.atdfrz.secondshop.mapper.CategoryMapper;
import com.atdfrz.secondshop.mapper.UserMapper;
import com.atdfrz.secondshop.pojo.Category;
import com.atdfrz.secondshop.pojo.User;
import com.atdfrz.secondshop.service.UserService;
import com.atdfrz.secondshop.service.ex.*;
import com.atdfrz.secondshop.controller.user.ex.FileEmptyException;
import com.atdfrz.secondshop.controller.user.ex.FileSizeException;
import com.atdfrz.secondshop.controller.user.ex.FileStateException;
import com.atdfrz.secondshop.controller.user.ex.FileTypeException;
import com.atdfrz.secondshop.controller.user.ex.FileUploadIOException;
import com.atdfrz.secondshop.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Controller
public class UserController extends BaseController {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private UserService userService;
    @Autowired(required = false)
    private UserMapper userMapper;
    @Autowired(required = false)
    private AddressMapper addressMapper;


//    @RequestMapping("/front/index")
//    public String index(){
//    return "/front/index";
//}

    @RequestMapping("/front/login")
    public String toLogin(){
        return "/front/login";}



    @RequestMapping("/login")
    @ResponseBody
    public JsonResult<Void> login(String username,String password,HttpSession session) {
        // 创建返回值
        JsonResult<Void> result = new JsonResult<Void>();
        try {
            User data = userService.login(username, password);
            //登录成功后，将userid和username存入到HttpSession中
            session.setAttribute("userid", data.getUserId());
            session.setAttribute("username", data.getUsername());
            session.setAttribute("email", data.getEmail());
            session.setAttribute("sex", data.getSex());
            session.setAttribute("phone", data.getPhone());
            session.setAttribute("photo", data.getPhoto());
            session.setAttribute("data", data);
            result.setState( 200 );
        } catch (UserNotFoundException e) {
            // 用户名未找到
            result.setState(4000);
            result.setMessage("该用户未注册！");
        } catch (PasswordNotMatchException e) {
            // 密码错误
            result.setState(5000);
            result.setMessage("密码输入有误！");
        }
        return result;
    }



    @RequestMapping("/register")
    @ResponseBody
    public JsonResult<Void> reg(User user) {
        // 创建返回值
        JsonResult<Void> result = new JsonResult<Void>();
        try {
            // 调用业务对象执行注册
            userService.reg(user);
            // 响应成功
            result.setState(200);
        } catch (UsernameDuplicateException e) {
            // 用户名
            result.setState(4000);
            result.setMessage("用户名已经被占用");
        } catch (InsertException e) {
            // 插入数据异常
            result.setState(5000);
            result.setMessage("注册失败，请联系系统管理员");
        }
        return result;
    }


    @RequestMapping("/front/reg")
    public String toreg(){return "/front/reg";}


    @RequestMapping("/front/remima")
    public String toremima(Model model){
        List<Category> category = categoryMapper.selectList(null);
        model.addAttribute("category",category);
        return "/front/remima";}

    @RequestMapping("/changePassWord")
    @ResponseBody
    public JsonResult<Void> changePassword(String oldPassword, String newPassword, HttpSession session) {
        // 调用session.getAttribute("")获取uid和username
        // 调用业务对象执行修改密码
        // 返回成功
//        System.out.println(oldPassword);
//        System.out.println(newPassword);
        Integer userid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
//        System.out.println(userid);
//        System.out.println(username);
            JsonResult<Void> result = new JsonResult<Void>();
            try {
                userService.changePassword(userid, username, oldPassword, newPassword);
                result.setState( 200 );
            } catch (PasswordNotMatchException e) {
                // 密码错误
                result.setState(5000);
                result.setMessage("原密码输入有误！");
            }
            return result;
        }

    @RequestMapping("/front/mygrxx")
    public String tomygrxx(Model model){
        List<Category> category = categoryMapper.selectList(null);
        model.addAttribute("category",category);
        return "/front/mygrxx";}


    @GetMapping("/getUserInfo")
    @ResponseBody
    public JsonResult<User> getByUid(HttpSession session) {
        // 从HttpSession对象中获取uid
        Integer uid = getUidFromSession(session);
        // 调用业务对象执行获取数据
        User data = userService.getByUid(uid);
        // 响应成功和数据
        return new JsonResult<User>(OK, data);
    }


    @RequestMapping("/changeUserInfo")
    @ResponseBody
    public JsonResult<Void> changeInfo(User user, HttpSession session) {
        // 从HttpSession对象中获取uid和username
        Integer userid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        // 调用业务对象执行修改用户资料
         userService.changeInfo(userid, username, user);
        // 响应成功
//        session.removeAttribute( "username");
        session.setAttribute(" username", username );
        return new JsonResult<Void>(OK);
        }


    /** 头像文件大小的上限值(10MB) */
    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;
    /** 允许上传的头像的文件类型 */
    public static final List<String> AVATAR_TYPES = new ArrayList<String>();

    /** 初始化允许上传的头像的文件类型 */
    static {
        AVATAR_TYPES.add("image/jpeg");
        AVATAR_TYPES.add("image/png");
        AVATAR_TYPES.add("image/bmp");
        AVATAR_TYPES.add("image/gif");
    }

    @PostMapping("/change_avatar")
    @ResponseBody
    public JsonResult<String> changeAvatar(@RequestParam("file") MultipartFile file, HttpSession session) {
        // 判断上传的文件是否为空
        if (file.isEmpty()) {
            // 是：抛出异常
            throw new FileEmptyException("上传的头像文件不允许为空");
        }

        // 判断上传的文件大小是否超出限制值
        if (file.getSize() > AVATAR_MAX_SIZE) { // getSize()：返回文件的大小，以字节为单位
            // 是：抛出异常
            throw new FileSizeException("不允许上传超过" + (AVATAR_MAX_SIZE / 1024) + "KB的头像文件");
        }

        // 判断上传的文件类型是否超出限制
        String contentType = file.getContentType();
        // boolean contains(Object o)：当前列表若包含某元素，返回结果为true；若不包含该元素，返回结果为false
        if (!AVATAR_TYPES.contains(contentType)) {
            // 是：抛出异常
            throw new FileTypeException("不支持使用该类型的文件作为头像，允许的文件类型：" + AVATAR_TYPES);
        }
        // 获取当前项目的绝对磁盘路径
        String parent ="D:\\upload\\" ;
        System.out.println(parent);

        File dir = new File(parent);
        if (!dir.exists()) {
            dir.mkdirs();
        }


        String suffix = "";
        String originalFilename = file.getOriginalFilename();
        int beginIndex = originalFilename.lastIndexOf(".");
        if (beginIndex > 0) {
            suffix = originalFilename.substring(beginIndex);
        }
        String filename = UUID.randomUUID().toString() + suffix;

        // 创建文件对象，表示保存的头像文件
        File dest = new File(dir, filename);
        // 执行保存头像文件
        try {
            file.transferTo(dest);
        } catch (IllegalStateException e) {
            // 抛出异常
            throw new FileStateException("文件状态异常，可能文件已被移动或删除");
        } catch (IOException e) {
            // 抛出异常
            throw new FileUploadIOException("上传文件时读写错误，请稍后重新尝试");
        }

        // 头像路径
        String photo = "/image/" + filename;
//        String photo = "C:/Users/黄鹏宇/AppData/Local/Temp/tomcat-docbase"+filename;
        // 从Session中获取uid和username
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        // 将头像写入到数据库中
        userService.changeAvatar(uid, username, photo);

        // 返回成功头像路径
        return new JsonResult<String>(OK, photo);
    }


//    @RequestMapping("/front/logout")
//    public String loginOut(HttpSession session){
//        session.invalidate();
//        return "redirect:/login.html";
//    }
     @GetMapping("/front/logout")
      public String logout(HttpSession session){
//          session.removeAttribute("user"); //退出登录则清除session中的用户信息
         session.invalidate();
          return "redirect:/front/login";
}

    @RequestMapping("/front/forget")
    public String toforget(){return "/front/forget";}


//    @RequestMapping("/forget")
//    @ResponseBody
//    public JsonResult<Void> forgetPassword(User user,String phone, String email,String newPassword, HttpSession session) {
//            // 调用session.getAttribute("")获取uid和username
//            // 调用业务对象执行修改密码
//            // 返回成
//            String username = getUsernameFromSession(session);
//            JsonResult<Void> result = new JsonResult<Void>();
//            try {
//                userService.forgetPassword( user,phone,email,newPassword,username );
//                result.setState( 200 );
//            } catch (PasswordNotMatchException e) {
//                // 密码错误
//                result.setState(5000);
//                result.setMessage("信息输入有误，请检查输入的信息！");
//            }
//            return result;
//        }


        @RequestMapping("/queryUserName")
        @ResponseBody
        public JsonResult<Void> queryUserName(HttpServletRequest request,HttpSession session){
//            String username = getUsernameFromSession(session);
            String username = request.getParameter( "username" );
            JsonResult<Void> result = new JsonResult<Void>();
            try {
                User data = userService.getByUserName( username );
//               userService.getByUserName( username );
                result.setState( 200 );

            } catch (UserNotFoundException e) {
                // 用户名输入有误
                result.setState(5000);
                result.setMessage("用户名输入有误！");
            }
            return result;
        }


    @RequestMapping("/queryContact")
    @ResponseBody
    public JsonResult<Void> queryContact(HttpServletRequest request,HttpSession session){
//            String username = getUsernameFromSession(session);
        String phone = request.getParameter( "phone" );
        String email = request.getParameter( "email" );
        JsonResult<Void> result = new JsonResult<Void>();
        try {
            User data = userService.getByPhoneAndEmail( phone,email);
            session.setAttribute("userid", data.getUserId());
            session.setAttribute("username", data.getUsername());
            result.setState( 200 );
        } catch (UserNotFoundException e) {
            // 用户名输入有误
            result.setState(5000);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    @RequestMapping("/forgetPassword")
    @ResponseBody
    public JsonResult<Void> forgetPassword(HttpServletRequest request, HttpSession session) {
        // 调用session.getAttribute("")获取uid和username
        // 调用业务对象执行修改密码
        // 返回成功
//        System.out.println(oldPassword);
//        System.out.println(newPassword);
//        Integer userid = getUidFromSession(session);
//        String username = getUsernameFromSession(session);
//        System.out.println(userid);
//        System.out.println(username);
        String newPassword = request.getParameter( "newPassword" );
        Integer userid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        JsonResult<Void> result = new JsonResult<Void>();
        try {
            userService.forgetPassword( userid,username,newPassword );
            result.setState( 200 );
        } catch (PasswordNotMatchException e) {
            // 密码错误
            result.setState(5000);
            result.setMessage("原密码输入有误！");
        }
        return result;
    }



    @RequestMapping("/front/bzproList")
    public String tobzproList(){return "/front/bzproList";}

//    @RequestMapping("/front/cart")
//    public String tocart(){return "/front/cart";}


    @RequestMapping("/front/address")
    public String toaddress(Model model){
        List<Category> category = categoryMapper.selectList(null);
        model.addAttribute("category",category);
        return "/front/address";}

//    @RequestMapping("/front/address1")
//    public String toaddress1(Model model){
//        List<Category> category = categoryMapper.selectList(null);
//        model.addAttribute("category",category);
//        return "address";}

    @RequestMapping("/front/getdecoration")
    public String todecoration(){return "/front/decoration";}

    @RequestMapping("/front/getflowerDer")
    public String toflowerDer(){return "/front/flowerDer";}



    @RequestMapping("/front/getidea")
    public String toidea(){return "/front/idea";}

    @RequestMapping("/front/mygxin")
    public String tomygxin(Model model){
        List<Category> category = categoryMapper.selectList(null);
        model.addAttribute("category",category);
        return "/front/mygxin";
    }


    @RequestMapping("/front/myprod")
    public String tomyprod(Model model){
        List<Category> category = categoryMapper.selectList(null);
        model.addAttribute("category",category);
        return "/front/myprod";}

    @RequestMapping("/front/ok")
    public String took(){return "/front/ok";}

//    @RequestMapping("/front/order")
//    public String toorder(){return "/front/order";}



    @RequestMapping("/front/getpaint")
    public String topaint(){return "/front/paint";}

    @RequestMapping("/front/getperfume")
    public String toperfume(){return "/front/perfume";}

    @RequestMapping("/front/proDetail")
    public String toproDetail(){return "/front/proDetail";}

    @RequestMapping("/front/proList")
    public String toproList(){return "/front/proList";}

    @RequestMapping("/front/vase_proList")
    public String tovaseproList(){return "/front/vase_proList";}

    @RequestMapping("/front/wuliu")
    public String towuliu(){return "/front/wuliu";}

    @RequestMapping("/front/zbproList")
    public String tozbproList(){return "/front/zbproList";}

    
}
